<template>
  <el-upload
    class="avatar-uploader"
    :action="baseUrl + '/question/upload'"
    name="file"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <!-- 
    是视频我们用video
    是图片我们用img
   -->
    <div v-if="type == 'img'">
      <img v-if="value" :src="baseUrl + '/' + value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </div>
    <div v-if="type == 'video'">
      <video
        v-if="value"
        :src="baseUrl + '/' + value"
        class="avatar"
        controls
      />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </div>
  </el-upload>
</template>

<script>
// 复制上传组件基本html、css、js
// 配置action与name
// 在上传前加入png允许上传

export default {
  props: ["value", "type"],
  data() {
    return {
      // type: '',  // img 表示图片   video表示 视频  没有值表示图片
      baseUrl: process.env.VUE_APP_URL,
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      // console.log('文件' ,res);
      this.$emit("input", res.data.url);
    },
    beforeAvatarUpload(file) {
      if (this.type == "img") {
        const isJPG = file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      } else {
        // 这里就是上传视频
        const isMP4 = file.type === "video/mp4";
        const isLt6M = file.size / 1024 / 1024 < 6;

        if (!isMP4) {
          this.$message.error("上传视频只能是 mp4 格式!");
        }
        if (!isLt6M) {
          this.$message.error("上传视频大小不能超过 6MB!");
        }
        return isMP4 && isLt6M;
      }
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
